package data;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import entities.Email;

public class EmailData {
	private static String apiKey = "27zBCmbpD27GcRuizpSK8I3ktkDl5848";
	
	public static List<Email> list(int page, int limit) {
		List<Email> emails = new ArrayList<Email>();
		
		int sk = (page -1) * limit;
		
		try {
			
			TreeMap<String, Object> params = new TreeMap<String, Object>();
			params.put("email", 1);
			
			String url = "http://api.mongolab.com/api/1/databases/emails/collections/email?s="+URLEncoder.encode(new Gson().toJson(params))+"&l="+limit+"&sk="+sk+"&apiKey=" + apiKey;
			InputStream input = new URL(url).openStream();
			Reader reader = new InputStreamReader(input, "UTF-8");
			
			Type listType = new TypeToken<List<Email>>(){}.getType();
			emails = new Gson().fromJson(reader, listType);
        } catch (MalformedURLException e) {
        	emails = new ArrayList<Email>();
            e.printStackTrace();
        } catch (IOException e) {
        	emails = new ArrayList<Email>();
        	e.printStackTrace();
        }
		
		return emails;
	}
	
	public static Email get(String id) {
		Email email = new Email();
		try {
			
			String url  = "http://api.mongolab.com/api/1/databases/emails/collections/email/" + id +"?apiKey=" + apiKey;
			InputStream input = new URL(url).openStream();
			Reader reader = new InputStreamReader(input, "UTF-8");
			email = new Gson().fromJson(reader, Email.class);
			
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
        	e.printStackTrace();
        }
		
		return email;
	}
	
	public static Email insert(Email email) {
		try {
            URL url = new URL("https://api.mongolab.com/api/1/databases/emails/collections/email?apiKey=" + apiKey);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("content-type", "application/json");
            connection.setRequestProperty("X-Custom-Header", "xxx");
            
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(new Gson().toJson(email));
            writer.close();
            
            
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            	String content = "";
    			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
    			while (1 == 1) {
    				String str = reader.readLine();
    				if (str == null)
    					break;
    				content += str;
    			}
    			
    			email = new Gson().fromJson(content, Email.class);
            } else {
                email = null;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
        	e.printStackTrace();
        }
		
		return email;
	}
	
	public static void delete(String id) {
		try {
			URL url = new URL("https://api.mongolab.com/api/1/databases/emails/collections/email/" + id +"?apiKey=" + apiKey);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("DELETE");
            connection.setRequestProperty("content-type", "application/json");
            connection.setRequestProperty("X-Custom-Header", "xxx");
            
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.close();
            
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            	String content = "";
    			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
    			while (1 == 1) {
    				String str = reader.readLine();
    				if (str == null)
    					break;
    				content += str;
    			}
    	
            } else {
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
        	e.printStackTrace();
        }
	}
	
	public static Email update(Email email) {
		try {
            URL url = new URL("https://api.mongolab.com/api/1/databases/emails/collections/email?apiKey=" + apiKey);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("PUT");
            connection.setRequestProperty("content-type", "application/json");
            connection.setRequestProperty("X-Custom-Header", "xxx");
            
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(new Gson().toJson(email));
            writer.close();
            
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            	String content = "";
    			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
    			while (1 == 1) {
    				String str = reader.readLine();
    				if (str == null)
    					break;
    				content += str;
    			}
    			
    			email = new Gson().fromJson(content, Email.class);
            } else {
                email = null;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
        	e.printStackTrace();
        }
		
		return email;
	}
	
	public static Email getByEmail(String emailAddress) {
		List<Email> emails = new ArrayList<Email>(); 
		Email email = new Email();
		try {
			
			TreeMap<String, String> params = new TreeMap<String, String>();
			params.put("email", emailAddress);
			String url = "http://api.mongolab.com/api/1/databases/emails/collections/email?q="+URLEncoder.encode(new Gson().toJson(params))+"&apiKey=" + apiKey;
			
			InputStream input = new URL(url).openStream();
			Reader reader = new InputStreamReader(input, "UTF-8");
            
			Type listType = new TypeToken<List<Email>>(){}.getType();
            emails = new Gson().fromJson(reader, listType);
			if (emails != null && emails.size() > 0) {
				email = emails.get(0);
			} else {
				email = null;
			}
        } catch (MalformedURLException e) {
        	email = null;
            e.printStackTrace();
        } catch (IOException e) {
        	email = null;
        	e.printStackTrace();
        }
		
		return email;
	}
	
	public static boolean checkExists(String emailAddress) {
		boolean exists = false;
		
		Email email = getByEmail(emailAddress);
		if (email != null) {
			exists = true;
		}
		
		return exists;
		
	}
}
